import { Injectable } from '@angular/core';
import { AppConfig } from "../config";
import { Headers, Http } from '@angular/http';
import { MenuAccess } from "../entity/menu_access.model";
import { InterceptorService } from '../service/interceptor/interceptor-service';

@Injectable()
export class MenuAccessService {
    private readonly param = "sysMenuAccesses";
    private get url(): string {
        return `${AppConfig.APP_RESTFUL}/${this.param}`;
    }
    constructor(private http: InterceptorService) { }

    getMenuAccessByroleId(roleId: number): Promise<MenuAccess[]> {
        // const url = `http://192.168.15.150:8585/webapi/v1/sysMenuAccesses/roleId/${roleId}`;
        return this.http.get(`${this.url}/roleId/${roleId}`)
            .toPromise()
            .then(response => {
                return response.json().data as MenuAccess[]
            })
            .catch(this.handleError);
    }

    // update(menuAccess: MenuAccess): Promise<MenuAccess> {
    //     // const url = `${this.url}`;
    //     const url = `http://192.168.15.150:8585/webapi/v1/sysMenuAccesses`;
    //     return this.http.put(url, JSON.stringify(menuAccess), { headers: this.headers })
    //         .toPromise()
    //         .then(() => menuAccess)
    //         .catch(this.handleError);
    // }

    firstCreate(menuAccess: MenuAccess): Promise<number> {
 
        return this.http                
          .post(`${this.url}/putSysMenuAccessAndShortCutByParent`, JSON.stringify(menuAccess))
          .toPromise()
          .then(res => res.json().code)
          .catch(this.handleError);
      }

    create(menuAccess: MenuAccess): Promise<number> {
        return this.http
          .post(`${this.url}/putSysMenuAccessAndShortCut`, JSON.stringify(menuAccess))
          .toPromise()
          .then(res => res.json().code)
          .catch(this.handleError);
      }


    private handleError(error: any): Promise<any> {
        return Promise.reject(error.message || error);
    }

}


// WEBPACK FOOTER //
// ./src/app/service/menu_access.service.ts